package com.clear.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.clear.subject.common.entity.PageResult;
import com.clear.subject.common.enums.IsDeletedFlagEnum;
import com.clear.subject.common.enums.SubjectCursorEnum;
import com.clear.subject.common.util.IdWorkerUtil;
import com.clear.subject.common.util.LoginUtil;
import com.clear.subject.domain.convert.SubjectInfoConverter;
import com.clear.subject.domain.entity.SubjectInfoBO;
import com.clear.subject.domain.entity.SubjectOptionBO;
import com.clear.subject.domain.handler.subject.SubjectTypeHandler;
import com.clear.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.clear.subject.domain.redis.RedisUtil;
import com.clear.subject.domain.service.SubjectInfoDomainService;
import com.clear.subject.domain.service.SubjectLabelDomainService;
import com.clear.subject.domain.service.SubjectLikedDomainService;
import com.clear.subject.infra.basic.entity.SubjectInfo;
import com.clear.subject.infra.basic.entity.SubjectInfoEs;
import com.clear.subject.infra.basic.entity.SubjectLabel;
import com.clear.subject.infra.basic.entity.SubjectMapping;
import com.clear.subject.infra.basic.service.SubjectEsService;
import com.clear.subject.infra.basic.service.SubjectInfoService;
import com.clear.subject.infra.basic.service.SubjectLabelService;
import com.clear.subject.infra.basic.service.SubjectMappingService;
import com.clear.subject.infra.entity.UserInfo;
import com.clear.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;
    // 注入工厂
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    private static final String RANK_KEY = "subject_rank";

    /**
     * 新增题目
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)   // 对多表操作，加事务
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        // 获取出题人昵称
        String loginId = LoginUtil.getLoginId();
        // =============================================================================
        // 假设我们都写在主流程中
        // 1.首先要判断type：单选调用单选的service、多选调用多选的service
        // 2.然后会有一大推的if-else

        // 我们这里采用 工厂 + 策略 的形式优化代码
        // 一个工厂包含了4种类型，根据传入的type自动映射选择自己的service
        // =============================================================================
        // 1）在subject_info表中插入
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETE.getCode());    // 设置未被删除
        subjectInfo.setSettleName(loginId);    // 出题人
        subjectInfoService.insert(subjectInfo); // todo 插入成功会将题目id写回到subjectInfo中，因此下一步可以拿到subject_id
        subjectInfoBO.setId(subjectInfo.getId());   // 将题目id传入subjectInfoBO
        // =============================================================================
        // 2）获取题目的类型（根据题目类型拿到对应策略（算法））
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        // 3）根据题目类型新增题目
        handler.add(subjectInfoBO);

        // 题目映射处理
        // 4）更新subject_mapping表：更新 分类id-标签id-题目id 的映射关系
        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappingList = new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETE.getCode());

                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);
        // ===========================同步到ES=========================================
        // todo 同步到ES有三种做法
        //      1、同步
        //      2、将新增发送到MQ，消费MQ完成同步
        //      3、利用canal，伪装成MySQL从节点监听binlog
        //   下面演示第一种
//        SubjectInfoEs subjectInfoEs = convert2SubjectEs();
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        // 雪花算法拿到唯一的doc_id
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectName(subjectInfoBO.getSubjectName());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());

        UserInfo userInfo = userRpc.getUserInfo(loginId);
        subjectInfoEs.setCreatedUser(userInfo.getNickName());

        subjectInfoEs.setCreatedTime(new Date().getTime());
        subjectInfoEs.setSubjectType(subjectInfoBO.getSubjectType());

        subjectEsService.insert(subjectInfoEs);

        // redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);

    }

    /**
     * 查询题目列表
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.getSubjectPage.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        // 在入参BO中拿值并写在返回的BO中
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();

        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        int count = subjectInfoService.countByCondition(subjectInfo,
                // fixme 传入两个该数据库表不存在的字段，有污染 后续再优化
                subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if (count == 0) {    // 查询不到记录，直接返回
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo,
                subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOList = SubjectInfoConverter.INSTANCE.convertInfoListToBOList(subjectInfoList);

        pageResult.setRecords(subjectInfoBOList);
        pageResult.setTotal(count);

        return pageResult;
    }

    /**
     * 查询题目详情
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.querySubjectInfo.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBOToInfo(subjectInfoBO);
        // 1）根据题目id查询题目信息
        SubjectInfo resultSubjectInfo = subjectInfoService.queryById(subjectInfo.getId());
        if (resultSubjectInfo == null) {    // 题目不存在，提前返回
            return null;
        }
        // 2）根据查到的题目信息，去拿到对应的题目详情
        Integer subjectType = resultSubjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        SubjectOptionBO subjectOptionBO = handler.query(subjectInfo.getId().intValue());    // 根据题目id去查题目详情（答案、题目选项等）

        SubjectInfoBO resultSubjectInfoBO = SubjectInfoConverter.INSTANCE.convertOptionBOAndInfoToInfoBO(subjectOptionBO, resultSubjectInfo);


        // a.根据题目id去查subject_mapping表得到所有labelId，然后再做转换 得到所有标签名称
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(resultSubjectInfoBO.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETE.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        log.info("SubjectInfoDomainServiceImpl.querySubjectInfo.subjectMappingList(labelIdList):{}", JSON.toJSONString(subjectMappingList));

        if (Optional.ofNullable(subjectMappingList).isPresent()) {
            List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIdList);
            if (Optional.ofNullable(subjectLabelList).isPresent()) {
                List<String> labelNameList = subjectLabelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
                resultSubjectInfoBO.setLabelNameList(labelNameList);
            }
        }

        // 题目详情点赞数据（当前用户是否点赞 该题目点赞总数）
        resultSubjectInfoBO.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        resultSubjectInfoBO.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));

        // 获取当前题目的游标（上一题、下一题id）
        assembleSubjectCursor(subjectInfoBO, resultSubjectInfoBO);

        log.info("SubjectInfoDomainServiceImpl.querySubjectInfo.resultSubjectInfoBO:{}", JSON.toJSONString(resultSubjectInfoBO));
        return resultSubjectInfoBO;
    }

    /**
     * 获取题目游标
     *
     * @param subjectInfoBO
     * @param bo
     */
    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, SubjectCursorEnum.NEXT_CURSOR.getCode());
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, SubjectCursorEnum.LAST_CURSOR.getCode());
        bo.setLastSubjectId(lastSubjectId);
    }

    /**
     * 全文检索：根据关键词查询
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectController.getSubjectPageBySearch.bo:{}", JSON.toJSONString(subjectInfoBO));
        }

        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageNo(subjectInfoBO.getPageSize());
//        subjectInfoEs.setSubjectType(subjectInfoBO.getSubjectType());

        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 查询题目贡献榜
     *
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
//        // 传统与数据库交互查排行榜
//        List<SubjectInfo> subjectInfoList = subjectInfoService.getContributeList();
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }

        List<SubjectInfoBO> subjectInfoBOList = new LinkedList<>();
        typedTuples.forEach(rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());   // 出题数

            // 发起远程调用，获取用户昵称
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());   // rank.getValue() == loginId
            subjectInfoBO.setCreateUser(userInfo.getNickName());    // 昵称
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());    // 头像

            subjectInfoBOList.add(subjectInfoBO);
        });

        return subjectInfoBOList;
    }
}
